package cn.kgc.shiro02.shiro;

import cn.kgc.shiro02.utils.ApplicationContextUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/4/4
 * @Description:
 */
public class RedisCache implements Cache {

    // 缓存的名字
    private String cacheName;

    public RedisCache(){}

    public RedisCache(String cacheName){
        this.cacheName = cacheName;
    }

    @Override
    public Object get(Object o) throws CacheException {
        RedisTemplate redisTemplate = getRedisTemplate();
        Object o1 = redisTemplate.opsForHash().get(cacheName, o.toString());
        return o1;
    }
    /*
    *   参数1  Object o  key
    *   参数2 Object o2  value
    * */
    @Override
    public Object put(Object o, Object o2) throws CacheException {
        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.opsForHash().put(cacheName,o.toString(),o2);
        return null;
    }

    @Override
    public Object remove(Object o) throws CacheException {

        RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.opsForHash().delete(cacheName, o.toString());
        return null;
    }

    @Override
    public void clear() throws CacheException {

    }

    @Override
    public int size() {
        RedisTemplate redisTemplate = getRedisTemplate();
        return redisTemplate.opsForHash().size(cacheName).intValue();
    }

    @Override
    public Set keys() {
        RedisTemplate redisTemplate = getRedisTemplate();
        Set keys = redisTemplate.opsForHash().keys(cacheName);
        return keys;
    }

    @Override
    public Collection values() {
        RedisTemplate redisTemplate = getRedisTemplate();
        List values = redisTemplate.opsForHash().values(cacheName);
        return values;
    }

    public RedisTemplate getRedisTemplate(){

        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }
}
